package org.jeecg.modules.question.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.jeecg.modules.question.entity.AoQuestion;
import org.jeecg.modules.question.entity.AoQuestionItem;
import org.jeecg.modules.question.mapper.AoQuestionItemMapper;
import org.jeecg.modules.question.mapper.AoQuestionMapper;
import org.jeecg.modules.question.service.IAoQuestionService;
import org.jeecg.modules.question.vo.AoQuestionChart;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;

/**
 * 题目表
 *
 * @author thankgod7
 * @version V1.0
 * @date 2022-01-18
 */
@Service
public class AoQuestionServiceImpl extends ServiceImpl<AoQuestionMapper, AoQuestion> implements IAoQuestionService {

    @Resource
    private AoQuestionMapper aoQuestionMapper;
    @Resource
    private AoQuestionItemMapper aoQuestionItemMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveMain(AoQuestion aoQuestion, List<AoQuestionItem> aoQuestionItemList) {
        aoQuestionMapper.insert(aoQuestion);
        if (aoQuestionItemList != null && aoQuestionItemList.size() > 0) {
            for (AoQuestionItem entity : aoQuestionItemList) {
                //外键设置
                entity.setQuestionId(aoQuestion.getId());
                aoQuestionItemMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateMain(AoQuestion aoQuestion, List<AoQuestionItem> aoQuestionItemList) {
        aoQuestionMapper.updateById(aoQuestion);

        //1.先删除子表数据
        aoQuestionItemMapper.deleteByMainId(aoQuestion.getId());

        //2.子表数据重新插入
        if (aoQuestionItemList != null && aoQuestionItemList.size() > 0) {
            for (AoQuestionItem entity : aoQuestionItemList) {
                //外键设置
                entity.setQuestionId(aoQuestion.getId());
                aoQuestionItemMapper.insert(entity);
            }
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delMain(String id) {
        aoQuestionItemMapper.deleteByMainId(id);
        aoQuestionMapper.deleteById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delBatchMain(Collection<? extends Serializable> idList) {
        for (Serializable id : idList) {
            aoQuestionItemMapper.deleteByMainId(id.toString());
            aoQuestionMapper.deleteById(id);
        }
    }

    @Override
    public List<AoQuestionChart> limit7groupByCreateTime() {
        return aoQuestionMapper.limit7groupByCreateTime();
    }

    @Override
    public List<AoQuestionChart> limit7groupByCategory() {
        return aoQuestionMapper.limit7groupByCategory();
    }

}
